<!DOCTYPE html>
<html lang="zh-CN">
{% load static %}
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>按年度统计发票报表</title>
    <!-- 引用本地static目录下的CSS文件 -->
    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/bootstrap-icons.css' %}">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        }
        .container-fluid {
            padding: 20px;
        }
        .card {
            border: none;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
        }
        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px 8px 0 0 !important;
            padding: 15px 20px;
        }
        .card-header h5 {
            margin: 0;
            font-weight: 600;
        }
        #chartContainer {
            height: 500px;
            padding: 20px;
        }
        .year-selector {
            background: white;
            padding: 15px 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            padding: 8px 24px;
            border-radius: 5px;
        }
        .btn-primary:hover {
            background: linear-gradient(135deg, #5568d3 0%, #6a4093 100%);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        .loading {
            text-align: center;
            padding: 50px;
            color: #667eea;
        }
    </style>
</head>
<body>
    <div id="app" class="container-fluid">
        <!-- 年份选择器 -->
        <div class="year-selector">
            <div class="row align-items-end">
                <div class="col-md-3">
                    <label for="yearInput" class="form-label">
                        <i class="bi bi-calendar3"></i> 选择基准年份
                    </label>
                    <input 
                        type="number" 
                        class="form-control" 
                        id="yearInput" 
                        v-model="selectedYear"
                        :min="2020"
                        :max="2030"
                        placeholder="请输入年份">
                </div>
                <div class="col-md-9">
                    <button class="btn btn-primary" @click="loadData">
                        <i class="bi bi-search"></i> 查询统计
                    </button>
                    <small class="text-muted ms-3">
                        <i class="bi bi-info-circle"></i> 
                        {% verbatim %}
                        将查询近3年数据：{{ selectedYear + 1 }}年、{{ selectedYear }}年、{{ selectedYear - 1 }}年
                        {% endverbatim %}
                    </small>
                </div>
            </div>
        </div>

        <!-- 图表容器 -->
        <div class="card">
            <div class="card-header">
                <h5>
                    <i class="bi bi-bar-chart-fill"></i> 
                    按年度统计发票报表（近3年对比）
                </h5>
            </div>
            <div class="card-body">
                <div v-show="loading" class="loading">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-3">正在加载数据...</p>
                </div>
                <div v-show="!loading" id="chartContainer"></div>
            </div>
        </div>
    </div>

    <!-- 引用本地static目录下的JS文件 -->
    <script src="{% static 'js/vue.global.js' %}"></script>
    <script src="{% static 'js/axios.min.js' %}"></script>
  <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <script>
        const { createApp } = Vue;

        createApp({
            data() {
                return {
                    selectedYear: new Date().getFullYear(), // 默认当前年份
                    loading: false,
                    chartInstance: null,
                    chartData: null
                };
            },
            mounted() {
                // 页面加载时自动查询当前年份数据
                this.loadData();
            },
            methods: {
                async loadData() {
                    this.loading = true;
                    try {
                        console.log('开始查询年份:', this.selectedYear);
                        const response = await axios.get('/api/invoice/data_year_statistics', {
                            params: {
                                year: this.selectedYear
                            }
                        });

                        console.log('后端响应:', response.data);

                        if (response.data.status === 'success') {
                            this.chartData = response.data.data;
                            console.log('图表数据:', this.chartData);
                            // 先关闭加载状态,然后等待DOM更新后再渲染图表
                            this.loading = false;
                            this.$nextTick(() => {
                                this.renderChart();
                            });
                        } else {
                            console.error('查询失败:', response.data.message);
                            alert('查询失败：' + response.data.message);
                            this.loading = false;
                        }
                    } catch (error) {
                        console.error('查询失败:', error);
                        alert('查询失败，请检查网络连接');
                        this.loading = false;
                    }
                },
                renderChart() {
                    console.log('开始渲染图表, chartData:', this.chartData);
                    
                    if (!this.chartData) {
                        console.error('图表数据为空');
                        return;
                    }

                    // 获取DOM元素
                    const chartDom = document.getElementById('chartContainer');
                    console.log('chartContainer DOM元素:', chartDom);
                    
                    if (!chartDom) {
                        console.error('chartContainer DOM元素不存在');
                        return;
                    }

                    // 初始化图表
                    if (this.chartInstance) {
                        this.chartInstance.dispose();
                    }
                    
                    try {
                        this.chartInstance = echarts.init(chartDom);
                        console.log('ECharts实例初始化成功');
                    } catch (error) {
                        console.error('ECharts初始化失败:', error);
                        return;
                    }

                    // 准备数据
                    const statistics = this.chartData.statistics;
                    console.log('statistics数据:', statistics);
                    
                    const years = statistics.map(item => item.year + '年');
                    const totalAmounts = statistics.map(item => item.total_amount);
                    const totalTaxes = statistics.map(item => item.total_tax);
                    const totalPriceTaxes = statistics.map(item => item.total_price_tax);
                    
                    console.log('years:', years);
                    console.log('totalAmounts:', totalAmounts);

                    // 配置选项
                    const option = {
                        title: {
                            text: `近3年发票统计对比（${this.chartData.years[2]}-${this.chartData.years[0]}）`,
                            left: 'center',
                            top: 10,
                            textStyle: {
                                fontSize: 18,
                                fontWeight: 600,
                                color: '#333'
                            }
                        },
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            },
                            formatter: (params) => {
                                let result = `<strong>${params[0].axisValue}</strong><br/>`;
                                params.forEach(item => {
                                    result += `${item.marker} ${item.seriesName}: ¥${item.value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}<br/>`;
                                });
                                return result;
                            }
                        },
                        legend: {
                            data: ['合计金额(不含税)', '合计税额', '价税合计'],
                            top: 45,
                            left: 'center',
                            itemWidth: 25,
                            itemHeight: 14
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            top: 100,
                            containLabel: true
                        },
                        xAxis: {
                            type: 'category',
                            data: years,
                            axisLabel: {
                                fontSize: 13,
                                color: '#666'
                            },
                            axisLine: {
                                lineStyle: {
                                    color: '#ddd'
                                }
                            }
                        },
                        yAxis: {
                            type: 'value',
                            name: '金额（元）',
                            nameTextStyle: {
                                fontSize: 13,
                                color: '#666'
                            },
                            axisLabel: {
                                formatter: (value) => {
                                    if (value >= 10000) {
                                        return (value / 10000).toFixed(1) + '万';
                                    }
                                    return value;
                                },
                                color: '#666'
                            },
                            splitLine: {
                                lineStyle: {
                                    color: '#f0f0f0'
                                }
                            }
                        },
                        series: [
                            {
                                name: '合计金额(不含税)',
                                type: 'bar',
                                data: totalAmounts,
                                itemStyle: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                        { offset: 0, color: '#83bff6' },
                                        { offset: 1, color: '#188df0' }
                                    ])
                                },
                                barWidth: '20%',
                                emphasis: {
                                    itemStyle: {
                                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                            { offset: 0, color: '#2378f7' },
                                            { offset: 1, color: '#156dd0' }
                                        ])
                                    }
                                }
                            },
                            {
                                name: '合计税额',
                                type: 'bar',
                                data: totalTaxes,
                                itemStyle: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                        { offset: 0, color: '#ffd666' },
                                        { offset: 1, color: '#ffc53d' }
                                    ])
                                },
                                barWidth: '20%',
                                emphasis: {
                                    itemStyle: {
                                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                            { offset: 0, color: '#ffb830' },
                                            { offset: 1, color: '#ffa500' }
                                        ])
                                    }
                                }
                            },
                            {
                                name: '价税合计',
                                type: 'bar',
                                data: totalPriceTaxes,
                                itemStyle: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                        { offset: 0, color: '#ff9c9c' },
                                        { offset: 1, color: '#f5222d' }
                                    ])
                                },
                                barWidth: '20%',
                                emphasis: {
                                    itemStyle: {
                                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                            { offset: 0, color: '#ff7875' },
                                            { offset: 1, color: '#cf1322' }
                                        ])
                                    }
                                }
                            }
                        ],
                        animationDuration: 1000,
                        animationEasing: 'cubicOut'
                    };

                    // 渲染图表
                    this.chartInstance.setOption(option);

                    // 响应式调整
                    window.addEventListener('resize', () => {
                        if (this.chartInstance) {
                            this.chartInstance.resize();
                        }
                    });
                }
            }
        }).mount('#app');
    </script>
</body>
</html>
